<?php
/**
 * Created by PhpStorm.
 * User: chenjunjie
 * Date: 2019/9/27
 * Time: 3:05 PM
 */

namespace App\Service;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use App\Model\ApiUser;
use Hyperf\Database\Model\ModelNotFoundException;
use Log;
class SmsService {

    /**
     * @param $mobile
     * @param $content
     * @param $blackId
     * @param $companyId
     * @return bool
     * @throws ClientException
     */
    public function send($mobile,$content,$blackId,$companyId){

        $this->sendAppNotify($mobile,$content,$blackId,$companyId);
        AlibabaCloud::accessKeyClient(env("OSS_ACCESS_ID"), env("OSS_ACCESS_SECRET"))
            ->regionId('cn-hangzhou')
            ->asDefaultClient();
        try {
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                // ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->host('dysmsapi.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId' => "cn-hangzhou",
                        'PhoneNumbers' => $mobile,
                        'SignName' => "鑫动",
                        'TemplateCode' => "SMS_198917238",
                        'TemplateParam' => $content,
                        'OutId' => "1",
                    ],
                ])
                ->request();
//            print_r($result->toArray());
            return true;
        } catch (ClientException $e) {
            Log::info("短信发送失败".$e->getErrorMessage());
            return false;
        } catch (ServerException $e) {
            Log::info("短信发送失败".$e->getErrorMessage());
            return false;
        }


    }

    public function sendAppNotify($mobile,$content,$blackId,$companyId){

        $mobiles = explode(',',$mobile);

        $contentJson = json_decode($content);

        $contentText = "黑名单预警提醒，%s在%s通过人脸设备识别考勤，属于%s黑名单人员，详情可到到鑫动管理后台查看";
        $contentText = sprintf($contentText,$contentJson->name,$contentJson->time,$contentJson->type);
        foreach ($mobiles as $item){
            try{
                $user = ApiUser::where('login_name',$item)->firstOrFail();
                $this->notify($user->id,0,$contentText,$blackId);
                $this->sendJpush($contentText,$user->registration_id,$user->app_device_type);
            }catch (ModelNotFoundException $exception){

            }
        }

        $this->notify(0,$companyId,$contentText,$blackId);


    }
    /**
     * 调用推送接口
     * @param $type
     * @param $userId
     * @param $companyId
     * @param $extInfo
     * @param $outerId
     */
    private function notify($userId,$companyId,$extInfo,$outerId){


        $type = 18;
        $postField = [
            'userId' => $userId,
            'companyId' => $companyId,
            'extInfo' => $extInfo,
            'outerId' => $outerId,
            'type' => $type,
        ];

        $url = env("PUSHER_SERVER_HOST").'/api/msg/notify';

        $resp = $this->curlPost($url,$postField);


        Log::info("发送消息url: ".$url);
        Log::info("发送消息",$postField);
        Log::info("发送消息resp :".$resp);
    }


    public function sendJpush($content,$registration_id,$app_device_type){


        if($registration_id){


            $title = '黑名单预警提醒';
            $postField = [
                'title' => $title,
                'content' => $content,
                'registrationId' => $registration_id,
                'platform' => $app_device_type,
            ];

            $url = env("PUSHER_SERVER_HOST").'/api/jpush/onePush';

            $resp = $this->curlPost($url,$postField);


            Log::info("jpush发送消息url: ".$url);
            Log::info("jpush发送消息",$postField);
            Log::info("jpush发送消息resp :".$resp);
        }

        return true;
    }
    /**
     * 通过CURL发送HTTP请求
     * @param string $url //请求URL
     * @param array $postFields //请求参数
     * @return mixed
     */
    private function curlPost($url,$postFields)
    {
        Log::info($url);
        Log::info($postFields);
        $postFields = http_build_query($postFields);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

}